package com.jeeplus.test.jlnu.student.controller;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfoHistory;
import com.jeeplus.test.jlnu.mailingInfo.domain.vo.MailingInfoVo;
import com.jeeplus.test.jlnu.student.domain.entity.*;
import com.jeeplus.test.jlnu.student.domain.result.NameAndPassword;
import com.jeeplus.test.jlnu.student.domain.vo.*;
import com.jeeplus.test.jlnu.student.dto.VerifyResponse;
import com.jeeplus.test.jlnu.student.service.*;
import com.jeeplus.test.tools.resp.Convert2Bean;
import com.jeeplus.test.tools.resp.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@Api(tags = "学生入口")
@RestController
@Slf4j
@RequestMapping("/student")
public class StudentController {

    /**
     * 本科-基本信息
     */
    @Autowired
    private BkStudentInfoService bkStudentInfoService;

    /**
     * 本科-履历信息
     */
    @Autowired
    private BkStudentResumeService bkStudentResumeService;

    /**
     * 本科/博士/硕士-奖惩信息
     */
    @Autowired
    private BkbsssStudentPrizeService bkbsssStudentPrizeService;

    @Autowired
    private BsssStudentRewardsService bsssStudentRewardsService;


    /**
     * 本科-家庭信息
     */
    @Autowired
    private BkStudentFamilyService bkStudentFamilyService;

    /**
     * 本科-毕业信息
     */
    @Autowired
    private BkStudentGraduateService bkStudentGraduateService;

    /**
     * 本科/博士/硕士-就业信息
     */
    @Autowired
    private BkbsssStudentObtainService bkbsssStudentObtainService;

    /**
     * 博士/硕士-基本信息
     */
    @Autowired
    private BsssStudentInfoService bsssStudentInfoService;

    /**
     * 博士/硕士-履历信息
     */
    @Autowired
    private BsssStudentResumeService bsssStudentResumeService;

    /**
     * 博士/硕士-家庭信息
     */
    @Autowired
    private BsssStudentFamilyService bsssStudentFamilyService;

    /**
     * 博士/硕士-毕业信息
     */
    @Autowired
    private BsssStudentGraduateService bsssStudentGraduateService;

    /**
     * 学籍变更
     */
    @Autowired
    private StudentStatusService studentStatusService;


    @Autowired
    private StudentApplyService studentApplyService;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private StudentInfoApproveService studentInfoApproveService;

    @ApiOperation("检查")
    @PostMapping("check")
    public ResponseEntity<NameAndPassword> check(String studentId, String idCard) {
        String roleIds = UserUtils.getCurrentUserDTO().getRoleIds();
        NameAndPassword nameAndPassword = null;
        nameAndPassword = bsssStudentInfoService.check(studentId, idCard);
//        if ("1846073793777348610".equals(roleIds)) {
//            nameAndPassword = bkStudentInfoService.check(studentId, idCard);
//        }
//        if ("1846073929899290625".equals(roleIds) || "1846074026565414913".equals(roleIds)) {
//            nameAndPassword = bsssStudentInfoService.check(studentId, idCard);
//        }
//
//        if ("1537767675223097346".equals(roleIds)) {
//            nameAndPassword = bkStudentInfoService.check(studentId, idCard);
//            if (nameAndPassword == null){
//                nameAndPassword = bsssStudentInfoService.check(studentId, idCard);
//            }
//        }

        return ResponseEntity.ok(nameAndPassword);
    }

    @ApiOperation("学生注册")
    @PostMapping("/studentRegistration")
    public R studentRegistration(@RequestBody BsssStudentInfo bsssStudentInfo){
        bsssStudentInfo.setPassword(SecurityUtils.encryptPassword(bsssStudentInfo.getPassword()));
        bsssStudentInfoService.save(bsssStudentInfo);
        return R.suc();
    }

    @ApiOperation("忘记密码验证")
    @PostMapping("studentForgotPasswordCheck")
    public R studentForgotPasswordCheck(@RequestBody BsssStudentInfoReqVo bsssStudentInfoReqVo) {
        BsssStudentInfo bsssStudentInfo = bsssStudentInfoService.studentForgotPasswordCheck(bsssStudentInfoReqVo);
        int checkNum = 0;
        if(bsssStudentInfo == null){
            return R.error("500","账号不存在，请核实账号！");
        }else{
            checkNum = bsssStudentInfoReqVo.getIdCardNumber().equals(bsssStudentInfo.getIdCardNumber()) ? ++checkNum : checkNum;
        }
        if (checkNum > 0 ){
            return R.suc();
        }
        return R.error("500","验证未通过！");
    }

    @ApiOperation("学生忘记密码")
    @PostMapping("/studentForgotPassword")
    public R studentForgotPassword(@RequestBody BsssStudentInfoReqVo bsssStudentInfoReqVo){
        BsssStudentInfo bsssStudentInfo = bsssStudentInfoService.studentForgotPasswordCheck(bsssStudentInfoReqVo);
        bsssStudentInfo.setPassword(SecurityUtils.encryptPassword(bsssStudentInfoReqVo.getPassword()));
        bsssStudentInfoService.updateById(bsssStudentInfo);
        return R.suc();
    }

    @ApiOperation("本科生-基本信息")
    @GetMapping("bkStudentInfo")
    public ResponseEntity<BkStudentInfoRespVo> getBkStudentInfo(String studentId, String idCard) {
        BkStudentInfo bkStudentInfo = bkStudentInfoService.getBkStudentInfo(studentId, idCard);
        return ResponseEntity.ok(Convert2Bean.convertBean(bkStudentInfo, BkStudentInfoRespVo.class));
    }

    @ApiOperation("本科生-基本信息修改")
    @PostMapping("bkStudentInfoUpdate")
    public R bkStudentInfoUpdate(@RequestBody BkStudentInfo bkStudentInfo) {
        return BooleanUtil.isTrue(bkStudentInfoService.bkStudentInfoUpdate(bkStudentInfo)) ? R.suc() : R.error();
    }

    @ApiOperation("本科生-履历信息")
    @GetMapping("bkStudentResume")
    public ResponseEntity<BkStudentResumeRespVo> getBkStudentResume(String studentId) {
        BkStudentResume bkStudentResume = bkStudentResumeService.getBkStudentResume(studentId);
        return ResponseEntity.ok(Convert2Bean.convertBean(bkStudentResume, BkStudentResumeRespVo.class));
    }

    @ApiOperation("本科生-履历信息修改")
    @PostMapping("bkStudentResumeUpdate")
    public R bkStudentResumeUpdate(@RequestBody BkStudentResume bkStudentResume) {
        return BooleanUtil.isTrue(bkStudentResumeService.bkStudentResumeUpdate(bkStudentResume)) ? R.suc() : R.error();
    }

    @ApiOperation("本科/博士/硕士-奖惩信息")
    @GetMapping("bkbsssStudentPrize")
    public ResponseEntity<BkbsssStudentPrizeRespVo> getBkbsssStudentPrize(String studentId, String flag) {
        BkbsssStudentPrize bkbsssStudentPrize = bkbsssStudentPrizeService.getBkbsssStudentPrize(studentId, flag);
        return ResponseEntity.ok(Convert2Bean.convertBean(bkbsssStudentPrize, BkbsssStudentPrizeRespVo.class));
    }

    @ApiOperation("本科/博士/硕士-奖惩信息修改")
    @PostMapping("bkbsssStudentPrizeUpdate")
    public R bkbsssStudentPrizeUpdate(@RequestBody BkbsssStudentPrize bkbsssStudentPrize) {
        return BooleanUtil.isTrue(bkbsssStudentPrizeService.bkbsssStudentPrizeUpdate(bkbsssStudentPrize)) ? R.suc() : R.error();
    }

    @ApiOperation("本科-家庭信息")
    @GetMapping("bkStudentFamily")
    public ResponseEntity<BkStudentFamilyRespVo> getBkStudentFamily(String studentId) {
        BkStudentFamily bkStudentFamily = bkStudentFamilyService.getBkStudentFamily(studentId);
        return ResponseEntity.ok(Convert2Bean.convertBean(bkStudentFamily, BkStudentFamilyRespVo.class));
    }

    @ApiOperation("本科-家庭信息修改")
    @PostMapping("bkStudentFamilyUpdate")
    public R bkStudentFamilyUpdate(@RequestBody BkStudentFamily bkStudentFamily) {
        return BooleanUtil.isTrue(bkStudentFamilyService.bkStudentFamilyUpdate(bkStudentFamily)) ? R.suc() : R.error();
    }


    @ApiOperation("本科-毕业信息")
    @GetMapping("bkStudentGraduate")
    public ResponseEntity<BkStudentGraduateRespVo> getBkStudentGraduate(String studentId) {
        BkStudentGraduate bkStudentGraduate = bkStudentGraduateService.getBkStudentGraduate(studentId);
        return ResponseEntity.ok(Convert2Bean.convertBean(bkStudentGraduate, BkStudentGraduateRespVo.class));
    }

    @ApiOperation("本科-毕业信息修改")
    @PostMapping("bkStudentGraduateUpdate")
    public R bkStudentGraduateUpdate(@RequestBody BkStudentGraduate bkStudentGraduate) {
        return BooleanUtil.isTrue(bkStudentGraduateService.bkStudentGraduateUpdate(bkStudentGraduate)) ? R.suc() : R.error();
    }


    @ApiOperation("本科/博士/硕士-就业信息")
    @GetMapping("bkbsssStudentObtain")
    public R getBkbsssStudentObtain(String studentId, String flag) {
        BkbsssStudentObtain bkbsssStudentObtain = bkbsssStudentObtainService.getBkbsssStudentObtain(studentId, flag);
        return R.suc(bkbsssStudentObtain);
    }

    @ApiOperation("本科/博士/硕士-就业信息修改")
    @PostMapping("bkbsssStudentObtainUpdate")
    public R bkbsssStudentObtainUpdate(@RequestBody BsssStudentGraduateVo bkbsssStudentObtain) {
        return BooleanUtil.isTrue(bkbsssStudentObtainService.bkbsssStudentObtainUpdate(bkbsssStudentObtain)) ? R.suc() : R.error();
    }

    @ApiOperation("博士/硕士-基本信息")
    @GetMapping("bsssStudentInfo")
    public ResponseEntity<BsssStudentInfoRespVo> getBsssStudentInfo(String studentId, String flag) {
        BsssStudentInfo bsssStudentInfo = bsssStudentInfoService.getBsssStudentInfo(studentId, flag);
        return ResponseEntity.ok(Convert2Bean.convertBean(bsssStudentInfo, BsssStudentInfoRespVo.class));
    }

    @ApiOperation("博士/硕士-基本信息修改")
    @PostMapping("bsssStudentInfoUpdate")
    public R bsssStudentInfoUpdate(@RequestBody BsssStudentInfo bsssStudentInfo) {
        return BooleanUtil.isTrue(bsssStudentInfoService.bsssStudentInfoUpdate(bsssStudentInfo)) ? R.suc() : R.error();
    }

    @ApiOperation("博士/硕士-履历信息")
    @GetMapping("bsssStudentResume")
    public ResponseEntity<BsssStudentResumeRespVo> getBsssStudentResume(String studentId, String flag) {
        BsssStudentResume bsssStudentResume = bsssStudentResumeService.getBsssStudentResume(studentId, flag);
        return ResponseEntity.ok(Convert2Bean.convertBean(bsssStudentResume, BsssStudentResumeRespVo.class));
    }

    @ApiOperation("博士/硕士-履历信息修改")
    @PostMapping("bsssStudentResumeUpdate")
    public R bsssStudentResumeUpdate(@RequestBody BsssStudentResume bsssStudentResume) {
        return BooleanUtil.isTrue(bsssStudentResumeService.bsssStudentResumeUpdate(bsssStudentResume)) ? R.suc() : R.error();
    }

    @ApiOperation("博士/硕士-家庭信息")
    @GetMapping("bsssStudentFamily")
    public ResponseEntity<BsssStudentFamilyRespVo> getBsssStudentFamily(String studentId, String flag) {
        BsssStudentFamily bsssStudentFamily = bsssStudentFamilyService.getBsssStudentFamily(studentId, flag);
        return ResponseEntity.ok(Convert2Bean.convertBean(bsssStudentFamily, BsssStudentFamilyRespVo.class));
    }

    @ApiOperation("博士/硕士-家庭信息修改")
    @PostMapping("bsssStudentFamilyUpdate")
    public R bkbsssStudentObtainUpdate(@RequestBody BsssStudentFamily bsssStudentFamily) {
        return BooleanUtil.isTrue(bsssStudentFamilyService.bkbsssStudentObtainUpdate(bsssStudentFamily)) ? R.suc() : R.error();
     }

    @ApiOperation("博士/硕士-毕业信息")
    @GetMapping("bsssStudentGraduate")
    public R getBsssStudentGraduate(@RequestParam String studentId, String flag) {
        BsssStudentGraduate bsssStudentGraduate = bsssStudentGraduateService.getBsssStudentGraduate(studentId, flag);
        return R.suc(bsssStudentGraduate);
    }

    @ApiOperation("博士/硕士-毕业信息修改")
    @PostMapping("bsssStudentGraduateUpdate")
    public R bsssStudentGraduateUpdate(@RequestBody BsssStudentGraduateVo bsssStudentGraduate) {
        return BooleanUtil.isTrue(bsssStudentGraduateService.bsssStudentGraduateUpdate(bsssStudentGraduate)) ? R.suc() : R.error();
    }

    @ApiOperation("学籍变更申请")
    @PostMapping("studentStatusChange")
    public R studentStatusChange(@RequestBody StudentStatus studentStatus) {
        return BooleanUtil.isTrue(studentStatusService.studentStatusChange(studentStatus)) ? R.suc() : R.error();
    }

    @ApiOperation("审批中心-分页")
    @PostMapping("examinePage")  // 需要传进来key  是 部门还是 学院
    public List<StudentApply> examinePage(StudentApply studentApply, int current, int size) {
        current = (current - 1) * size;
        List<StudentApply> studentApplies = new ArrayList<>();
        String roleIds = UserUtils.getCurrentUserDTO().getRoleIds();
        String officeId = UserUtils.getCurrentUserDTO().getOfficeDTO().getId();
        if (roleIds.equals("1854767206064549890") || roleIds.equals("1854767309747744769")) {
            studentApplies = studentApplyService.examinePage1(studentApply, current, size);
        }
        if (officeId.equals("1854766833937510402")) {
            studentApplies = studentApplyService.examinePage2(studentApply, current, size);
        }
        if (officeId.equals("1537767675223097346")) {
            studentApplies.addAll(studentApplyService.examinePage1(studentApply, current, size));
            studentApplies.addAll(studentApplyService.examinePage2(studentApply, current, size));
        }
        return studentApplies;
    }

    @ApiOperation("学籍变更-分页")
    @PostMapping("examinePageResult")
    public List<StudentApply> examinePageResult(StudentApply studentApply, int current, int size) {
        current = (current - 1) * size;
        List<StudentApply> studentApplies = studentApplyService.examinePageResult(studentApply, current, size);
        return studentApplies;
    }


    @ApiOperation("学籍变更申请- 审批")
    @PostMapping("studentStatusApply")
    public R studentStatusApply(String id, String status) {
        return BooleanUtil.isTrue(studentStatusService.studentStatusApply(id, status)) ? R.suc() : R.error();
    }

    @ApiOperation("学籍变更申请- 记录")
    @GetMapping("record")
    public R groupingByInfoId(@RequestParam("infoId") Long infoId) {
        if (infoId == null) {
            return R.error("9999","参数为空");
        }
        List<ChangeStuInfoHistory.GroupedChangeHistory> result = bsssStudentInfoService.groupingByInfoId(infoId);
        return R.suc(result);
    }


    @ApiOperation("图片上传")
    @PostMapping("/imgUpload")
    //接收最多10个文件
    public R imgUpload(@RequestParam("file") MultipartFile file,@RequestParam("studentId") String studentId, @RequestParam("type") String type) {
        return bsssStudentInfoService.imgUpload(file,studentId,type);
    }

    @ApiOperation("学生账户查询")
    @GetMapping("/selectStudentInfoPage")
    //接收最多10个文件
    public Page<BsssStudentInfo> selectStudentInfoPage(BsssStudentInfo bsssStudentInfo,
                                   @RequestParam(defaultValue=  "1") int pageNum,
                                   @RequestParam(defaultValue = "10") int pageSize) {
        Page<BsssStudentInfo> page = new Page<>(pageNum, pageSize);
        Page<BsssStudentInfo> pageResult = bsssStudentInfoService.selectStudentInfoListPage(bsssStudentInfo, page);
        return pageResult;
    }

    @ApiOperation("学生密码修改")
    @PostMapping("/changePassword")
    //接收最多10个文件
    public R changePassword(@RequestBody BsssStudentInfo bsssStudentInfo) {
        int result = bsssStudentInfoService.changePassword(bsssStudentInfo);
        if(result <=0){
            return R.error("9999","修改失败");
        }
        return R.suc();
    }


    @ApiOperation("批量添加履历信息")
    @PostMapping("/save")
    public R save(@RequestBody Map<String, Object> requestData) {
        return bsssStudentResumeService.addBsssStudentResume(requestData);
    }


    @ApiOperation("单个添加履历信息")
    @PostMapping("/add")
    public R save(@RequestBody BsssStudentResume bsssStudentResume) {
        int i = bsssStudentResumeService.add(bsssStudentResume);
        if(i == 1){
            return R.suc();
        }else {
            return R.error("9999","添加失败");
        }

    }


    @ApiOperation("查询履历信息")
    @GetMapping("/bsssStudentResumeList")
    public R bsssStudentResumeList(@RequestParam("studentId") String studentId) {
        List<BsssStudentResume> list =  bsssStudentResumeService.bsssStudentResumeList(studentId);
        return R.suc(list);
    }

    @ApiOperation("删除履历信息")
    @GetMapping("/deleteBsssStudentResume")
    public R deleteBsssStudentResume(@RequestParam int id) {
        int i =  bsssStudentResumeService.deleteResumeById(id);
        if(i == 1){
            return R.suc();
        }else {
            return R.error("9999","删除失败");
        }
    }

    @ApiOperation("修改履历信息")
    @PostMapping("/updateBsssStudentResume")
    public R updateBsssStudentResume(@RequestBody BsssStudentResume bsssStudentResume) {
        int i = bsssStudentResumeService.updateResumeById(bsssStudentResume);
        if(i == 1){
            return R.suc();
        }else {
            return R.error("9999","修改成功");
        }
    }

    @ApiOperation("自传编辑")
    @PostMapping("/batchUpdateByStudentIds")
    public R batchUpdateByStudentIds(@RequestBody BsssStudentResume bsssStudentResume) {
        int i = bsssStudentResumeService.batchUpdateByStudentIds(bsssStudentResume);
        if(i > 0){
            return R.suc();
        }else {
            return R.error("9999","保存失败");
        }
    }

    @ApiOperation("新增奖惩信息")
    @PostMapping("/saveRewards")
    public R saveRewards(@RequestBody BsssStudentRewards bsssStudentRewards) {
        return (bsssStudentRewardsService.saveRewards(bsssStudentRewards) > 0) ? R.suc() : R.error();
    }

    @ApiOperation("删除奖惩信息")
    @PostMapping("/deleteRewards")
    public R saveRewards(@RequestBody List<Long> ids) {
        return (bsssStudentRewardsService.deleteRewards(ids) > 0) ? R.suc() : R.error();
    }

    @ApiOperation("奖惩信息修改")
    @PostMapping("/updateRewards")
    public R updateRewards(@RequestBody BsssStudentRewards bsssStudentRewards) {
        return (bsssStudentRewardsService.updateRewards(bsssStudentRewards) > 0) ? R.suc() : R.error();
    }

    @ApiOperation("查询奖惩信息")
    @GetMapping("/getRewards")
    public R getRewards(@RequestParam String studentId) {
        if(studentId == null || studentId.isEmpty()){
            return R.error("9999","无效参数");
        }
        List<BsssStudentRewards> list =  bsssStudentRewardsService.getRewards(studentId);
        return R.suc(list);
    }



    @ApiOperation("新增家庭成员信息")
    @PostMapping("/saveStudentFamily")
    public R saveStudentFamily(@RequestBody BsssStudentFamily bsssStudentFamily) {
        return (bsssStudentFamilyService.saveStudentFamily(bsssStudentFamily) > 0) ? R.suc() : R.error();
    }


    @ApiOperation("删除家庭成员信息")
    @PostMapping("/deleteStudentFamily")
    public R deleteStudentFamily(@RequestBody List<Long> ids) {
        return (bsssStudentFamilyService.deleteStudentFamily(ids) > 0) ? R.suc() : R.error();
    }

    @ApiOperation("修改家庭成员信息")
    @PostMapping("/updateStudentFamily")
    public R updateRewards(@RequestBody BsssStudentFamily bsssStudentFamily) {
        return (bsssStudentFamilyService.updateStudentFamily(bsssStudentFamily) > 0) ? R.suc() : R.error();
    }

    @ApiOperation("查询家庭成员信息")
    @GetMapping("/getStudentFamily")
    public R getStudentFamily(@RequestParam String studentId) {
        if(studentId == null || studentId.isEmpty()){
            return R.error("9999","无效参数");
        }
        List<BsssStudentFamily> list =  bsssStudentFamilyService.getStudentFamily(studentId);
        return R.suc(list);
    }

    @ApiOperation("基本信息表填充")
    @PostMapping("/basicInfoForm")
    public void basicInfoForm(HttpServletResponse response, @RequestBody BsssStudentInfo bsssStudentInfo) throws IOException {
        StudentInfoApprove data = studentInfoApproveService.getStudentInfo(bsssStudentInfo.getStudentId(),"1",bsssStudentInfo.getFlag());
        if (data == null) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();

        try {
            VerifyResponse verifyResponse = mapper.readValue(data.getContent(), VerifyResponse.class);
            response.setContentType("text/html; charset=UTF-8");
            Map<String, Object> variables = new HashMap<>();
            variables.put("name", verifyResponse.getName());
            variables.put("gender", verifyResponse.getGender());
            variables.put("studentUrl", verifyResponse.getStudentUrl());
            variables.put("birthDate", verifyResponse.getBirthDate());
            variables.put("ethnicity", verifyResponse.getEthnicity());
            variables.put("photo", verifyResponse.getPhoto());

            variables.put("approvalStatus", data.getApprovalStatus());
            variables.put("approvalRemark", data.getApprovalRemark());
            variables.put("outsideType", data.getOutsideType());

            //需要加学院

            variables.put("academicMajor", verifyResponse.getAcademicMajor());
            variables.put("studentId", verifyResponse.getStudentId());
            variables.put("contactNumber", verifyResponse.getContactNumber());
            variables.put("idCardNumber", verifyResponse.getIdCardNumber());
            variables.put("height", verifyResponse.getHeight());
            variables.put("familyDetailedAddress", verifyResponse.getFamilyDetailedAddress());
            variables.put("postalCode", verifyResponse.getPostalCode());

            List<BsssStudentFamily> bsssStudentFamilyList = bsssStudentFamilyService.getStudentFamily(bsssStudentInfo.getStudentId());


            List<BsssStudentFamily> dataList = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                BsssStudentFamily family = (i < bsssStudentFamilyList.size())
                        ? bsssStudentFamilyList.get(i)
                        : new BsssStudentFamily(); // 空对象用于占位
                dataList.add(family);

            }

            variables.put("familyInfo", dataList);


//            // 获取审批状态
//            int approvalStatus = data.getApprovalStatus();
//            String approvalRemark = data.getApprovalRemark();
//            // 将状态添加到响应头
//            response.setHeader("X-Approval-Status", String.valueOf(approvalStatus));
//            response.setHeader("X-Approval-Remark", approvalRemark);
            // 渲染模板
            String html = templateEngine.process("checklists", new Context(Locale.CHINA, variables));
            response.getWriter().write(html);
            response.getWriter().flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }







    @ApiOperation("学籍表字段填充")
    @PostMapping("/academicForm")
    public void academicForm(HttpServletResponse response, @RequestBody BsssStudentInfo bsssStudentInfo) throws IOException {
        StudentInfoApprove data = studentInfoApproveService.getStudentInfo(bsssStudentInfo.getStudentId(),"3",bsssStudentInfo.getFlag());
        if (data == null) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();

        if(bsssStudentInfo.getFlag().equals("1")){
            try {
                VerifyResponse verifyResponse = mapper.readValue(data.getContent(), VerifyResponse.class);
                response.setContentType("text/html; charset=UTF-8");
                Map<String, Object> variables = new HashMap<>();
                variables.put("name", verifyResponse.getName());
                variables.put("birthDate", verifyResponse.getBirthDate());
                variables.put("gender", verifyResponse.getGender());
                variables.put("studentUrl", verifyResponse.getStudentUrl());
                variables.put("ethnicity", verifyResponse.getEthnicity());
                variables.put("politicalAffiliation", verifyResponse.getPoliticalAffiliation());
                variables.put("interests", verifyResponse.getInterests());
                variables.put("hometown", verifyResponse.getHometown());
                variables.put("originLocation", verifyResponse.getOriginLocation());
                variables.put("educationSystem", verifyResponse.getEducationSystem());
                variables.put("idCardNumber", verifyResponse.getIdCardNumber());
                variables.put("familyDetailedAddress", verifyResponse.getFamilyDetailedAddress());
                variables.put("applySchools", verifyResponse.getApplySchools());
                variables.put("photo", verifyResponse.getPhoto());

                variables.put("approvalStatus", data.getApprovalStatus());
                variables.put("approvalRemark", data.getApprovalRemark());
                variables.put("outsideType", data.getOutsideType());



                List<BsssStudentRewards> bsssStudentRewardsList = bsssStudentRewardsService.getRewards(bsssStudentInfo.getStudentId());
                List<BsssStudentRewards> dataList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    BsssStudentRewards rewards = (i < bsssStudentRewardsList.size())
                            ? bsssStudentRewardsList.get(i)
                            : new BsssStudentRewards(); // 空对象用于占位
                    dataList.add(rewards);

                }

                List<BsssStudentResume> bsssStudentResumeList = bsssStudentResumeService.bsssStudentResumeList(bsssStudentInfo.getStudentId());
                List<BsssStudentResume> resumeList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    BsssStudentResume resume = (i < bsssStudentResumeList.size())
                            ? bsssStudentResumeList.get(i)
                            : new BsssStudentResume(); // 空对象用于占位
                    resumeList.add(resume);
                }


                List<BsssStudentFamily> bsssStudentFamilyList = bsssStudentFamilyService.getStudentFamily(bsssStudentInfo.getStudentId());
                List<BsssStudentFamily> familyList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    BsssStudentFamily family = (i < bsssStudentFamilyList.size())
                            ? bsssStudentFamilyList.get(i)
                            : new BsssStudentFamily(); // 空对象用于占位
                    familyList.add(family);

                }

                variables.put("rewardsInfo", dataList);
                variables.put("familyInfo", familyList);
                variables.put("resumeInfo", resumeList);
                String html = templateEngine.process("ugForm", new Context(Locale.CHINA, variables));
                response.getWriter().write(html);
                response.getWriter().flush();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                VerifyResponse verifyResponse = mapper.readValue(data.getContent(), VerifyResponse.class);
                response.setContentType("text/html; charset=UTF-8");
                Map<String, Object> variables = new HashMap<>();

                variables.put("departmentName", verifyResponse.getDepartmentName());
                variables.put("name", verifyResponse.getName());
                variables.put("gender", verifyResponse.getGender());
                variables.put("studentId", verifyResponse.getStudentId());
                variables.put("birthDate", verifyResponse.getBirthDate());
                variables.put("hometown", verifyResponse.getHometown());
                variables.put("politicalAffiliation", verifyResponse.getPoliticalAffiliation());
                variables.put("maritalStatus", verifyResponse.getMaritalStatus());
                variables.put("academicMajor", verifyResponse.getAcademicMajor());
                variables.put("disciplineCategory", verifyResponse.getDisciplineCategory());
                variables.put("admissionCategory", verifyResponse.getAdmissionCategory());
                variables.put("idCardNumber", verifyResponse.getIdCardNumber());
                variables.put("previousEducation", verifyResponse.getPreviousEducation());
                variables.put("previousSchoolMajor", verifyResponse.getPreviousSchoolMajor());
                variables.put("wechatId", verifyResponse.getWechatId());
                variables.put("specialties", verifyResponse.getSpecialties());
                variables.put("qqId", verifyResponse.getQqId());
                variables.put("email", verifyResponse.getEmail());

                variables.put("studentUrl", verifyResponse.getStudentUrl());
                variables.put("ethnicity", verifyResponse.getEthnicity());
                variables.put("interests", verifyResponse.getInterests());
                variables.put("originLocation", verifyResponse.getOriginLocation());
                variables.put("educationSystem", verifyResponse.getEducationSystem());
                variables.put("familyDetailedAddress", verifyResponse.getFamilyDetailedAddress());
                variables.put("applySchools", verifyResponse.getApplySchools());
                variables.put("photo", verifyResponse.getPhoto());
                variables.put("approvalStatus", data.getApprovalStatus());
                variables.put("approvalRemark", data.getApprovalRemark());
                variables.put("outsideType", data.getOutsideType());
                List<BsssStudentResume> bsssStudentResumes = bsssStudentResumeService.bsssStudentResumeList(verifyResponse.getStudentId());
                if(!bsssStudentResumes.isEmpty()){
                    BsssStudentResume bsssStudentResume = bsssStudentResumes.get(0);
                    variables.put("youthLeagueJoinInfo", bsssStudentResume.getYouthLeagueJoinInfo());
                    variables.put("partyJoinInfo", bsssStudentResume.getPartyJoinInfo());
                }





                List<BsssStudentResume> bsssStudentResumeList = bsssStudentResumeService.bsssStudentResumeList(bsssStudentInfo.getStudentId());
                List<BsssStudentResume> resumeList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    BsssStudentResume resume = (i < bsssStudentResumeList.size())
                            ? bsssStudentResumeList.get(i)
                            : new BsssStudentResume(); // 空对象用于占位
                    resumeList.add(resume);
                }


                List<BsssStudentFamily> bsssStudentFamilyList = bsssStudentFamilyService.getStudentFamily(bsssStudentInfo.getStudentId());
                List<BsssStudentFamily> familyList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    BsssStudentFamily family = (i < bsssStudentFamilyList.size())
                            ? bsssStudentFamilyList.get(i)
                            : new BsssStudentFamily(); // 空对象用于占位
                    familyList.add(family);

                }

                variables.put("familyInfo", familyList);
                variables.put("resumeInfo", resumeList);
                String html = templateEngine.process("ugForm", new Context(Locale.CHINA, variables));
                response.getWriter().write(html);
                response.getWriter().flush();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @ApiOperation("毕业登记表字段填充")
    @PostMapping("/generateInfoForm")
    public void generateForm(HttpServletResponse response, @RequestBody BsssStudentInfo bsssStudentInfo) throws IOException {
        StudentInfoApprove data = studentInfoApproveService.getStudentInfo(bsssStudentInfo.getStudentId(),"2",bsssStudentInfo.getFlag());
        if (data == null) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();

        try {
            VerifyResponse verifyResponse = mapper.readValue(data.getContent(), VerifyResponse.class);
            response.setContentType("text/html; charset=UTF-8");
            Map<String, Object> variables = new HashMap<>();
            variables.put("educationSystem", verifyResponse.getEducationSystem());
            variables.put("departmentName", verifyResponse.getDepartmentName());
            variables.put("academicMajor", verifyResponse.getAcademicMajor());
            variables.put("name", verifyResponse.getName());


            variables.put("gender", verifyResponse.getGender());
            variables.put("birthDate", verifyResponse.getBirthDate());
            variables.put("politicalAffiliation", verifyResponse.getPoliticalAffiliation());
            variables.put("ethnicity", verifyResponse.getEthnicity());
            variables.put("healthStatus", verifyResponse.getHealthStatus());
            variables.put("hometown", verifyResponse.getHometown());
            variables.put("previousDegree", verifyResponse.getPreviousDegree());
            variables.put("familyDetailedAddress", verifyResponse.getFamilyDetailedAddress());
            variables.put("foreignLanguage", verifyResponse.getForeignLanguage());
            variables.put("learningSituation", verifyResponse.getLearningSituation());
            variables.put("practiceUnit", verifyResponse.getPracticeUnit());
            variables.put("learningContent", verifyResponse.getLearningContent());
            variables.put("thesisTitle", verifyResponse.getThesisTitle());
            variables.put("graduationDesign", verifyResponse.getGraduationDesign());
            variables.put("personalEvaluation", verifyResponse.getPersonalEvaluation());


            variables.put("studentUrl", verifyResponse.getStudentUrl());

            variables.put("approvalStatus", data.getApprovalStatus());
            variables.put("approvalRemark", data.getApprovalRemark());
            variables.put("outsideType", data.getOutsideType());

            //需要加学院

            variables.put("studentId", verifyResponse.getStudentId());
            variables.put("contactNumber", verifyResponse.getContactNumber());
            List<BsssStudentFamily> bsssStudentFamilyList = bsssStudentFamilyService.getStudentFamily(bsssStudentInfo.getStudentId());


            List<BsssStudentResume> bsssStudentResumeList = bsssStudentResumeService.bsssStudentResumeList(bsssStudentInfo.getStudentId());
            List<BsssStudentResume> resumeList = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                BsssStudentResume resume = (i < bsssStudentResumeList.size())
                        ? bsssStudentResumeList.get(i)
                        : new BsssStudentResume(); // 空对象用于占位
                resumeList.add(resume);
            }

            List<BsssStudentFamily> dataList = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                BsssStudentFamily family = (i < bsssStudentFamilyList.size())
                        ? bsssStudentFamilyList.get(i)
                        : new BsssStudentFamily(); // 空对象用于占位
                dataList.add(family);
            }
            if(bsssStudentResumeList.size() > 0){
                variables.put("autobiography", bsssStudentResumeList.get(0).getAutobiography());
            }
            List<BsssStudentRewards> bsssStudentRewardsList = bsssStudentRewardsService.getRewards(bsssStudentInfo.getStudentId());
            List<BsssStudentRewards> rewardsList = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                BsssStudentRewards rewards = (i < bsssStudentRewardsList.size())
                        ? bsssStudentRewardsList.get(i)
                        : new BsssStudentRewards(); // 空对象用于占位
                rewardsList.add(rewards);

            }
            variables.put("familyInfo", dataList); //家庭关系
            variables.put("resumeInfo", resumeList);//个人简历
            variables.put("rewardsInfo", rewardsList);//奖惩信息



            String html = templateEngine.process("registrationForm", new Context(Locale.CHINA, variables));
            response.getWriter().write(html);
            response.getWriter().flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    @ApiOperation("研究生学籍PDF字段填充")
//    @PostMapping("/pgForm-pdf")
//    public void pgFormPdf(HttpServletResponse response, @RequestBody BsssStudentInfo bsssStudentInfo) throws IOException {
//        StudentInfoApprove data = studentInfoApproveService.getStudentInfo(bsssStudentInfo.getStudentId(),"3",bsssStudentInfo.getFlag());
//        if (data == null) {
//            return;
//        }
//        ObjectMapper mapper = new ObjectMapper();
//
//
//
//    }



    @ApiOperation("就业信息表字段填充")
    @PostMapping("/forwardForm")
    public void forwardForm(HttpServletResponse response, @RequestBody BsssStudentInfo bsssStudentInfo) throws IOException {
        StudentInfoApprove data = studentInfoApproveService.getStudentInfo(bsssStudentInfo.getStudentId(),"4",bsssStudentInfo.getFlag());
        if (data == null) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();


            try {
                VerifyResponse verifyResponse = mapper.readValue(data.getContent(), VerifyResponse.class);
                response.setContentType("text/html; charset=UTF-8");
                Map<String, Object> variables = new HashMap<>();
                variables.put("collegeName", verifyResponse.getCollegeName());
                variables.put("academicMajor", verifyResponse.getAcademicMajor());
                variables.put("studentId", verifyResponse.getStudentId());
                variables.put("name", verifyResponse.getName());
                variables.put("approvalStatus", data.getApprovalStatus());
                variables.put("approvalRemark", data.getApprovalRemark());
                variables.put("outsideType", data.getOutsideType());
                variables.put("idCardNumber", verifyResponse.getIdCardNumber());
                variables.put("educationLevel", verifyResponse.getEducationLevel());
                variables.put("contactNumber", verifyResponse.getContactNumber());
                variables.put("fileReceivingUnitName", verifyResponse.getFileReceivingUnitName());
                variables.put("fileReceivingUnitAddress", verifyResponse.getFileReceivingUnitAddress());
                variables.put("fileReceiver", verifyResponse.getFileReceiver());
                variables.put("receiverPhone", verifyResponse.getReceiverPhone());
                String html = templateEngine.process("forwardForm", new Context(Locale.CHINA, variables));
                response.getWriter().write(html);
                response.getWriter().flush();

            } catch (Exception e) {
                e.printStackTrace();


        }
    }

    @ApiOperation("学籍变更")
    @PostMapping("addStudentInfoApprove")
    public void addStudentInfoApprove(@RequestBody BsssStudentInfo bsssStudentInfo) {
         bsssStudentInfoService.addStudentInfoApprove(bsssStudentInfo);
    }

    @ApiOperation("信息表提交")
    @PostMapping("submitForm")
    public R submitForm(@RequestBody ApprovalForm approvalForm) {
        int count = studentInfoApproveService.updateType(approvalForm);
        if(count > 0){
           return R.suc();
        }else {
           return R.error("9999","已全部提交请务重复操作");
        }
    }

    @ApiOperation("信息表审核")
    @PostMapping("approve")
    public R approve(@RequestBody ApprovalForm approvalForm) {
        int count = studentInfoApproveService.approve(approvalForm);
        if(count > 0){
            return R.suc();
        }else {
            return R.error("9999","审批失败");
        }
    }
    @PostMapping("/BkbsssStudentObtain/batchUpdate")
    public ResponseEntity<?> batchUpdate(@RequestBody BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo){
        try{
            boolean success = bkbsssStudentObtainService.batchUpdate(bkbsssStudentObtainReqVo);
            if(success){
                return ResponseEntity.ok().body("批量更新成功");
            }else {
                return ResponseEntity.badRequest().body("批量更新失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }catch (Exception e){
            return ResponseEntity.internalServerError().body("服务器错误: " + e.getMessage());
        }
    }
    @PostMapping("/BkbsssStudentObtain/saveOrUpdate")
    public ResponseEntity<Boolean> saveOrUpdateBkbsssStudentObtain(@RequestBody BkbsssStudentObtain bkbsssStudentObtain
    ){
        boolean result = bkbsssStudentObtainService.saveOrUpdateBkbsssStudentObtain(bkbsssStudentObtain);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
    @DeleteMapping("/BkbsssStudentObtain/batchDelete")
    public ResponseEntity <String> delete(String ids){
        String idArray[] = ids.split(",");
        bkbsssStudentObtainService.removeByIds(Lists.newArrayList ( idArray ) );
        return ResponseEntity.ok("200");
    }
    @GetMapping("/BkbsssStudentObtain/list")
    public IPage<BkbsssStudentObtain> selectAllBkbsssStudentObtainVOs(
            BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ){
        Page<BkbsssStudentObtain> page = new Page<>(pageNum,pageSize);
        Page<BkbsssStudentObtain> pageResult = bkbsssStudentObtainService.selectAllBkbsssStudentObtainVOs(bkbsssStudentObtainReqVo,page);
        return pageResult;
    }
    @GetMapping("/BkbsssStudentObtain/{id}")
    public ResponseEntity<BkbsssStudentObtainReqVo> selectBkbsssStudentObtainById(@PathVariable Long id){
        BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo = bkbsssStudentObtainService.selectBkbsssStudentObtainById(id);
        if(bkbsssStudentObtainReqVo == null){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(bkbsssStudentObtainReqVo);
    }
    @PostMapping("/BkbsssStudentObtain/DataDowload")
    public ResponseEntity<byte[]> DataDowload(@RequestBody List<String> ids){
        return bkbsssStudentObtainService.DataDowload(ids);
    }
    //本科生基本信息数据查询 参数（flag）
    @ApiOperation("本科生数据查询")
    @GetMapping("getBsssStudentInfoPage")
    public Page<BsssStudentInfo> getBsssStudentInfoPage(BsssStudentInfoReqVo bsssStudentInfoReqVo,
                                                        @RequestParam(defaultValue = "1") int pageNum,
                                                        @RequestParam(defaultValue = "10") int pageSize) {
        Page<BsssStudentInfo> page = new Page<>(pageNum, pageSize);
        Page<BsssStudentInfo> pageResult = bsssStudentInfoService.getBsssStudentInfoPage(bsssStudentInfoReqVo,page);
        return pageResult;
    }

    @ApiOperation("本科生-基本信息查询")
    @GetMapping("getStudentByStudentId")
    public R getStudentByStudentId(BsssStudentInfoReqVo bsssStudentInfoReqVo) {
        BsssStudentInfo bsssStudentInfo = bsssStudentInfoService.getStudentByStudentId(bsssStudentInfoReqVo);
        if(bsssStudentInfo == null){
            return R.error("9999","数据为空");
        }
        return R.suc(bsssStudentInfo);
    }


    //本科生履历信息分页查询
    @ApiOperation("本科生履历信息分页查询")
    @GetMapping("getResumeInfoPage")
    public Page<BsssStudentResume> getResumeInfoPage(BsssStudentResume bsssStudentResume,
                                                     @RequestParam(defaultValue = "1") int pageNum,
                                                     @RequestParam(defaultValue = "10") int pageSize) {
        Page<BsssStudentResume> page = new Page<>(pageNum, pageSize);
        Page<BsssStudentResume> pageResult = bsssStudentResumeService.getResumeInfoPage(bsssStudentResume,page);
        return pageResult;
    }

    //本科生履历信息详情
    @ApiOperation("本科生履历信息详情")
    @GetMapping("getResumeInfoByStudentId")
    public R getResumeInfoByStudentId(BsssStudentResume bsssStudentResume) {
        BsssStudentResume bsssStudentResumeInfo = bsssStudentResumeService.getStudentResumeByStudentId(bsssStudentResume);
        if(bsssStudentResumeInfo == null){
            return R.error("9999","数据为空");
        }
        return R.suc(bsssStudentResumeInfo);
    }


    //本科生-硕士-研究生分页查询
    @ApiOperation("本科生-硕士-研究生分页查询")
    @GetMapping("getStudentInfoPage")
    public Page<StudentField> getStudentInfoPage(StudentField studentField,
                                                 @RequestParam(defaultValue = "1") int pageNum,
                                                 @RequestParam(defaultValue = "10") int pageSize) {
        Page<StudentField> page = new Page<>(pageNum, pageSize);
        Page<StudentField> pageResult = bsssStudentInfoService.getStudentInfoPage(studentField,page);
        return pageResult;
    }


    //本科生-硕士-研究生信息详情
    @ApiOperation("本科生-硕士-研究生信息详情")
    @GetMapping("getStudentData")
    public R getStudentData(StudentField studentField) {
        StudentField studentFieldInfo = bsssStudentInfoService.getStudentData(studentField);
        if(studentFieldInfo == null){
            return R.error("9999","数据为空");
        }
        return R.suc(studentFieldInfo);
    }



    //批量移交
    @ApiOperation("批量移交")
    @PostMapping("/batchUpdateObtain")
    public R batchUpdateObtain(@RequestBody BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo) {
        // 参数校验
        if (CollectionUtils.isEmpty(bkbsssStudentObtainReqVo.getTransferStateList())) {
            return R.error("9999", "请选择需要移交的数据");
        }
        bkbsssStudentObtainService.batchUpdateMailing(bkbsssStudentObtainReqVo);
        return R.suc();
    }


}
